package com.xbts.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.SeiMaterial;
import com.xbts.system.domain.SeiTemplate;
import com.xbts.system.mapper.SeiMaterialMapper;
import com.xbts.system.mapper.SysRoleMapper;
import com.xbts.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xbts.system.service.ISeiMaterialService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 基本信息表Service业务层处理
 *
 * @author xbts
 * @date 2023-08-24
 */
@Service
public class SeiMaterialServiceImpl extends ServiceImpl<SeiMaterialMapper, SeiMaterial> implements ISeiMaterialService {

    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SeiMaterialMapper materialMapper;

    /**
     * 树状查询素材
     *
     * @return 素材列表
     */
    @Override
    public List<SeiMaterial> selectMaterialList(SeiMaterial seiMaterial) {
        String name = seiMaterial.getName();
        if(StringUtils.isNotBlank(name)){
            return this.list(new LambdaQueryWrapper<SeiMaterial>()
                    .ne(SeiMaterial::getType, 3)
                    .like(SeiMaterial::getName, name));
        }
        // 查询所有素材
        List<SeiMaterial> list = this.list(new LambdaQueryWrapper<SeiMaterial>()
                .ne(SeiMaterial::getType, 3));

        Map<String, SeiMaterial> seiMaterialMap = list.stream().collect(Collectors.toMap(SeiMaterial::getMaterialId, v -> v));

        List<SeiMaterial> materialTree = new ArrayList<>();
        for (SeiMaterial temp : list) {

            if(temp.getType() == 3) continue;

            String parentId = temp.getParentId();
            if(StringUtils.isBlank(parentId) || "0".equals(parentId)) {
                materialTree.add(temp);
                continue;
            }

            SeiMaterial material = seiMaterialMap.get(temp.getParentId());
            if(StringUtils.isNotNull(material)){
                material.getChildren().add(temp);
            }
        }
        return materialTree;
    }

    /**
     * 查询素材表
     *
     * @return 素材列表
     */
    @Override
    public List<SeiMaterial> selectMaterial() {
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        List<SeiMaterial> table = list(queryWrapper);
        List<SeiMaterial> result = new ArrayList<>();
        for (SeiMaterial seiMaterial : table) {
            String[] parentIds = seiMaterial.getAncestors().split(",");
            if (parentIds.length == 3) {
                seiMaterial.setGrandparent(parentIds[1]);
                seiMaterial.setParentName(getById(parentIds[2]).getName());
                seiMaterial.setAffiliationName(sysUserService.selectUserById(seiMaterial.getMaterialAffiliation()).getUserName());
                result.add(seiMaterial);
            }
        }
        return result;
    }

    /**
     * 条件查询
     *
     * @return 素材列表
     */
    @Override
    public List<SeiMaterial> searchMaterialList(SeiMaterial seiMaterial) {
        seiMaterial.setType(3);
        return materialMapper.searchMaterialList(seiMaterial.queryWrapper());
    }

    /**
     * 查询模板类型
     *
     * @return 素材列表
     */
    @Override
    public List<SeiMaterial> selectMaterialType(SeiMaterial seiMaterial) {
        List<SeiMaterial> table = selectMaterialList(seiMaterial);
        List<SeiMaterial> result = new ArrayList<>();
        for (SeiMaterial material : table) {
            if (material.getName().contains(seiMaterial.getName())) {
                result.add(material);
            }
        }
        return result;
    }

    /**
     * 递归查找子集id
     */
    private List<String> selectChildren(String materialId) {
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        List<SeiMaterial> table = list(queryWrapper);
        List<String> ids = new ArrayList<>();
        for (SeiMaterial son : table) {
            if (son.getParentId().equals(materialId)) {
                ids.add(son.getMaterialId());
                ids.addAll(selectChildren(son.getMaterialId()));
            }
        }
        return ids;
    }

    /**
     * 修改素材
     *
     * @param seiMaterial 素材
     * @return 结果
     */
    @Override
    public boolean updateMaterial(SeiMaterial seiMaterial) {
        if (getById(seiMaterial.getMaterialId()).getMaterialAffiliation().equals(SecurityUtils.getUserId())) {
            UpdateWrapper<SeiMaterial> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("material_id", seiMaterial.getMaterialId());
            seiMaterial.setUpdateBy(SecurityUtils.getUserId().toString());
            seiMaterial.setUpdateTime(DateUtils.getNowDate());
            return update(seiMaterial, updateWrapper);
        } else {
            throw new ServiceException("没有权限修改");
        }
    }

    /**
     * 新增素材类型
     *
     * @param name 素材标题
     * @return 结果
     */
    @Override
    public boolean insertMaterialType(String name) {
        if (name == null) {
            throw new ServiceException("名称不能为空");
        }
        SeiMaterial seiMaterial = new SeiMaterial();
        seiMaterial.setCreateBy(SecurityUtils.getUserId().toString());
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        if (getOne(queryWrapper.eq("name", name)) != null) {
            throw new ServiceException("重复素材类型名称");
        }
        seiMaterial.setMaterialAffiliation(SecurityUtils.getUserId());
        seiMaterial.setParentId("0");
        seiMaterial.setType(1);
        seiMaterial.setName(name);
        seiMaterial.setAncestors("0");
        return save(seiMaterial);
    }

    /**
     * 新增素材
     *
     * @param seiMaterial 素材
     * @return 结果
     */
    @Override
    public boolean addSon(SeiMaterial seiMaterial) {
        seiMaterial.setMaterialAffiliation(SecurityUtils.getUserId());
        seiMaterial.setCreateBy(SecurityUtils.getUserId().toString());
        seiMaterial.setCreateTime(new Date());
        seiMaterial.setAncestors(getById(seiMaterial.getParentId()).getAncestors() + "," + seiMaterial.getParentId());
        return save(seiMaterial);
    }

    /**
     * 删除素材
     *
     * @param materialId 素材Id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMaterial(String materialId) {
        String userType = SecurityUtils.getLoginUser().getUser().getUserType();
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        SeiMaterial seiMaterial = getOne(queryWrapper.eq("material_id", materialId));
        if("02".equals(userType)){
            if (!seiMaterial.getMaterialAffiliation().equals(SecurityUtils.getUserId())) {
                throw new ServiceException("只能删除自己的素材或素材类型！");

            }
        }
        List<String> ids = selectChildren(seiMaterial.getMaterialId());
        if(ids.size() > 0){
            throw new ServiceException("存在子类型，不可删除！");
        }
        return removeById(materialId);
    }

    /**
     * 批量删除素材
     *
     * @param ids 素材Id集合
     * @return 结果
     */
    @Transactional
    @Override
    public boolean batchDeleteMaterial(List<String> ids) {
        for (String materialId : ids) {
            deleteMaterial(materialId);
        }
        return true;
    }

    /**
     * 查询素材详情
     *
     * @param materialId 素材主键
     * @return 素材
     */
    @Override
    public SeiMaterial selectSeiMaterialById(String materialId) {
        return getById(materialId);
    }

    /**
     * 查询一级
     *
     * @return 素材
     */
    @Override
    public List<SeiMaterial> selectGrandParent() {
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper.eq("parent_id", 0));
    }

    /**
     * 查询一级
     *
     * @return 素材
     */
    @Override
    public List<SeiMaterial> selectParent(String parentId) {
        QueryWrapper<SeiMaterial> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper.eq("parent_id", parentId));
    }

    @Override
    public boolean addMaterial(SeiMaterial seiMaterial) {
        seiMaterial.setType(3);
        seiMaterial.setMaterialAffiliation(SecurityUtils.getUserId());
        SeiMaterial materialParent = this.getById(seiMaterial.getParentId());
        if(StringUtils.isNull(materialParent)) throw new ServiceException("二级类型不存在");
        seiMaterial.setGrandparent(materialParent.getParentId());
        return this.save(seiMaterial);
    }
}
